package com.rpay.admin.config.jwt;

import com.rpay.admin.util.render.JsonRender;
import com.rpay.common.enums.PcsResultCode;
import com.rpay.common.vo.PcsResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p/>
 */
public class NoAuthenticationEntryPoint implements AuthenticationEntryPoint {


    //当访问的资源没有权限，会调用这里
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {
        if ("options".equalsIgnoreCase(request.getMethod())) {
            String origin = request.getHeader("Origin");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.setStatus(PcsResultCode.SUCCESS.getCode());
            response.addHeader("Access-Control-Allow-Origin", origin);
            response.addHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
            //*response.addHeader("Access-Control-Allow-Headers","Content-Type");*//*
            response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization");
            response.addHeader("Access-Control-Allow-Credentials", "true");
            response.addHeader("Vary", "Origin");
            response.setHeader("Access-Control-Max-Age", String.valueOf(1800));
//            PcsResult.build(PcsResultCode.SUCCESS);
//            Output outPut = CommonUtils.buildSuccessMessage("");
            new JsonRender().render(request, response, PcsResult.build(PcsResultCode.SUCCESS));
        } else {
            //返回json形式的错误信息
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.setStatus(PcsResultCode.METHOD_TYPE_NOT_SUPPORT.getCode());
            //RestResp restResp = new RestResp(RestResp.NO_SESSION, "没有登录或登录已过期!");
//            Output outPut = CommonUtils.buildFailMessage("没有登录或登录已过期!");
//            Output outPut = CommonUtils.buildFailMessage("没有登录或登录已过期!");
            PcsResult pcsResult = PcsResult.build(PcsResultCode.NOT_FOUND_HANDLER.getCode(), "没有登录或登录已过期");
            new JsonRender().render(request, response, pcsResult);
        }
    }
}